﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;

namespace SilverPOP.Library.Utilities
{
    public class ExcelHelper
    {
        public static void ExportListToExcel<T>(List<T> listToExport, string xlsName)
        {
            

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
            HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=" + xlsName + ".xls");

            Int32 success = 0;
            string sep = "";
            try
            {
                PropertyInfo[] fieldInfo = listToExport[0].GetType().GetProperties();
                foreach (PropertyInfo col in fieldInfo)
                {
                    HttpContext.Current.Response.Write(sep + col.Name);
                    sep = "\t";
                }
                HttpContext.Current.Response.Write("\n");

                foreach (T dataItem in listToExport)
                {
                    PropertyInfo[] allProperties = dataItem.GetType().GetProperties();
                    sep = "";
                    foreach (PropertyInfo thisProperty in allProperties)
                    {
                        object value = thisProperty.GetValue(dataItem, null);
                        String propetyValue = (value == null ? String.Empty : value.ToString());
                        HttpContext.Current.Response.Write(sep + propetyValue.ToString());
                        sep = "\t";
                    }
                    ++success;
                    HttpContext.Current.Response.Write("\n");
                }
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    
    }
}